<?php
namespace app\custom_user\controller;

use app\common\controller\ApiBaseController;
use app\custom_user\model\UserModel;
use app\custom_user\model\MobileCodeModel;
use app\custom_user\logic\UserLogic;
use app\custom_user\model\UserSession;

/**
 * 用户相关的接口
 */
class ApiController extends ApiBaseController
{
    protected function _initialize()
    {
        parent::_initialize();
        $token=input("token");
        if($token){
            UserSession::init($token);
        }
    }
    protected function checkLogin()
    {
        $user=UserSession::get("user");
        if(!$user){
            $this->error("用户未登录",url("login"));
        }
        return $user;
    }
    //退出登录
    public function logout()
    {
        $ul=new UserLogic;
        UserSession::clear();
        $this->success();
    }
    //删除用户
    public function remove()
    {
        $user=$this->checkLogin();
        $ul=new UserLogic;
        $result=$ul->remove($user["id"]);
        if(!$result){
            $this->error($ul->getError());
        }
        $this->success();
    }
    //获取当前用户的信息
    public function getUserInfo()
    {
        $user=$this->checkLogin();
        $this->result($user,1);
    }
    //修改用户信息(基本信息)
    public function updateInfo()
    {
        $user=$this->checkLogin();
        $ul=new UserLogic;
        $result=$ul->updateInfo($user,$_REQUEST);
        if(!$result){
            $this->error($ul->getError());
        }
        $this->success();
    }
    //修改用户密码
    public function updatePassword()
    {
        $user=$this->checkLogin();
        $ul=new UserLogic;
        $result=$ul->updatePassword($user,$_REQUEST);
        if(!$result){
            $this->error($ul->getError());
        }
        $this->success();
    }
    //发送绑定手机号的手机验证码
    public function sendBindMobileCode()
    {
        $mobile=input("mobile");
        if(!$mobile){
            $this->error("手机号不能为空");
        }
        //检查手机号有没有被占用
        $um=new UserModel();
        $record=$um->where(["mobile"=>$mobile])->find();
        if($record){
            $this->error("手机号已被占用");
        }
        $mcm=new MobileCodeModel();
        $result=$mcm->send($mobile,"bind mobile");
        if(!$result){
            $this->error($mcm->getError());
        }
        $this->success("发送成功");
    }
}
